﻿using ExcelUnity.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace ExcelUnity.Importer.Results
{
    public class ImportResult
    {
        public ImportResult(Exception exception, string bookError)
        {
            Exception = exception;
            BooktError = bookError;
        }

        public ImportResult(List<ResultSheet> sheets) => Sheets = sheets;

        public ImportResult(CsvResultSheet sheet) => Sheets = new List<ResultSheet> { sheet };

        public List<ResultSheet>? Sheets { get; set; }

        public Exception? Exception { get; private set; }

        /// <summary>
        /// Excel本身存在的错误
        /// </summary>
        public string? BooktError { get; private set; }

        /// <summary>
        /// 导入成功
        /// </summary>
        public bool ImportSuccess => string.IsNullOrWhiteSpace(SummaryError);

        /// <summary>
        /// 所有错误
        /// </summary>
        public string? SummaryError
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(BooktError)) return BooktError;

                var errors = Sheets?.Where(x => !x.IsValidated).Select(x => $"{x.SheetDisplayName}:{Environment.NewLine}{x.SummaryError}");
                if (errors.IsNotNullOrEmpty())
                    return string.Join(Environment.NewLine, errors);

                return null;
            }
        }

        /// <summary>
        /// 无法展示在excel中的错误信息
        /// </summary>
        public string? NotDisplayError
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(BooktError)) return BooktError;

                var errors = Sheets?.Where(p => !string.IsNullOrWhiteSpace(p.SheetError))
                                   .Select(m => $"{m.SheetDisplayName}:{Environment.NewLine}{m.SheetError}");

                if (errors.IsNotNullOrEmpty())
                    return string.Join(Environment.NewLine, errors);

                return null;
            }
        }

        public List<T>? GetDataModelAsList<T>(int sheetIndex = 0)
        {
            if (Sheets.IsNullOrEmpty() || Sheets!.Count <= sheetIndex)
                return null;

            return Sheets![sheetIndex].GetDataModelAsList<T>();
        }


        public DataTable? GetDataModelAsDataTable(int sheetIndex = 0)
        {
            if (Sheets.IsNullOrEmpty() || Sheets!.Count <= sheetIndex)
                return null;

            return Sheets![sheetIndex].GetDataModelAsDataTable();
        }
    }
}
